﻿using B.Auth.APi.Application.Command.Menus;
using B.Auth.APi.Application.Command.Role;
using B.Auth.Domain.Entity;
using B.Auth.Domain.Repository;
using B.Auth.Enum;
using MediatR;

namespace B.Auth.APi.Application.CommandHand.Menuss
{

    public class GetRoleidCommandHand : IRequestHandler<GetRoleidCommand, ApiResult<List<MenuModel>>>
    {

        private readonly IBaseRepository<RoleUser> _roleuser;
        private readonly IBaseRepository<RoleMenuModel> _roleMeuModel;
        private readonly IBaseRepository<MenuModel> _menu;


        public GetRoleidCommandHand(IBaseRepository<RoleUser> roleuser, IBaseRepository<RoleMenuModel> roleMeuModel, IBaseRepository<MenuModel> menu)
        {
            _roleuser = roleuser;
            _roleMeuModel = roleMeuModel;
            _menu = menu;
        }

        public Task<ApiResult<List<MenuModel>>> Handle(GetRoleidCommand request, CancellationToken cancellationToken)
        {
            var result=new ApiResult<List<MenuModel>>();
            List<int> Roleid = _roleuser.GetAll().Where(x => x.UserId == request.uid).Select(x => x.RoleId).ToList();
            
            List<int> Menuids = new List<int>();
            foreach (var item in Roleid)
            {
                List<int> menuid = _roleMeuModel.GetAll().Where(x => x.RID == item).Select(x => x.MID).ToList();

                Menuids.AddRange(menuid);
            }

            List<MenuModel> menus=new List<MenuModel>();
            foreach (var item in Menuids.Distinct())
            {

                var m = _menu.GetAll().Where(x => x.Id == item&&x.MenuDel==0).ToList();
                menus.AddRange(m);

            }


            result.data = menus.ToList();
            return Task.FromResult(result);

            
        }
    }
}
